// 文件上传相关功能
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('script_file');
const fileList = document.getElementById('fileList');
const fileCount = document.getElementById('fileCount');

// 只在存在文件上传相关元素时添加事件监听
if (dropZone && fileInput) {
    // 拖放文件处理
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        handleFiles(e.dataTransfer.files);
    });

    // 点击上传区域触发文件选择
    dropZone.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择处理
    fileInput.addEventListener('change', (e) => {
        handleFiles(e.target.files);
    });
}

// 处理选择的文件
function handleFiles(files) {
    if (!fileList || !fileCount) return;
    
    fileList.innerHTML = '';
    Array.from(files).forEach(file => {
        const item = document.createElement('div');
        item.className = 'file-list-item';
        item.textContent = file.name;
        fileList.appendChild(item);
    });
    fileCount.textContent = `已选择 ${files.length} 个文件`;
}

// 添加历史记录管理
const HISTORY_KEY = 'script_run_history';

function saveRunHistory(scriptName, data, duration) {
    let history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '{}');
    if (!history[scriptName]) {
        history[scriptName] = [];
    }
    
    // 限制每个脚本保存最近的10条记录
    if (history[scriptName].length >= 10) {
        history[scriptName].pop();
    }
    
    history[scriptName].unshift({
        timestamp: Date.now(),
        duration: duration,
        data: data
    });
    
    localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
}

function showHistoryDialog(scriptName) {
    const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '{}');
    const records = history[scriptName] || [];
    
    // 创建对话框
    const dialog = document.createElement('div');
    dialog.className = 'history-dialog';
    dialog.innerHTML = `
        <div class="history-dialog-content">
            <div class="history-dialog-header">
                <h3>运行历史记录 - ${scriptName}</h3>
                <button class="close-btn">&times;</button>
            </div>
            <div class="history-list">
                ${records.length === 0 ? '<div class="no-history">暂无运行记录</div>' : 
                    records.map((record, index) => `
                        <div class="history-item ${record.data.error || record.data.returncode !== 0 ? 'error' : 'success'}">
                            <div class="history-item-header">
                                <span class="history-timestamp">
                                    ${new Date(record.timestamp).toLocaleString()}
                                </span>
                                <span class="history-duration">
                                    运行时间: ${record.duration}s
                                </span>
                                <button class="expand-history-btn" onclick="toggleHistoryDetail(${index})">
                                    展开详情
                                </button>
                            </div>
                            <div class="history-detail" id="history-detail-${index}">
                                ${formatRunResult(record.data)}
                            </div>
                        </div>
                    `).join('')}
            </div>
        </div>
    `;
    
    // 添加关闭功能
    const closeBtn = dialog.querySelector('.close-btn');
    closeBtn.onclick = () => {
        document.body.removeChild(dialog);
    };
    
    // 点击外部关闭
    dialog.onclick = (e) => {
        if (e.target === dialog) {
            document.body.removeChild(dialog);
        }
    };
    
    document.body.appendChild(dialog);
}

function formatRunResult(data) {
    if (data.error) {
        return `<div class="error-message">${data.error}</div>`;
    }
    
    let output = '';
    if (data.stdout) {
        output += `
            <div class="output-section">
                <div class="output-header">标准输出:</div>
                <pre class="output-content">${data.stdout}</pre>
            </div>`;
    }
    if (data.stderr) {
        output += `
            <div class="output-section error">
                <div class="output-header">错误输出:</div>
                <pre class="output-content">${data.stderr}</pre>
            </div>`;
    }
    if (data.returncode !== 0) {
        output += `<div class="return-code">退出代码: ${data.returncode}</div>`;
    }
    return output || '<div class="no-output">无输出内容</div>';
}

function toggleHistoryDetail(index) {
    const detail = document.getElementById(`history-detail-${index}`);
    const btn = detail.previousElementSibling.querySelector('.expand-history-btn');
    const isExpanded = detail.classList.toggle('expanded');
    btn.textContent = isExpanded ? '收起详情' : '展开详情';
}

// 脚本运行功能
function runScript(scriptName) {
    const outputContainer = document.getElementById(`output-${scriptName}`);
    const fileSelect = document.getElementById(`file-${scriptName}`);
    const selectedFile = fileSelect.value;
    const runBtn = document.querySelector(`[onclick="runScript('${scriptName}')"]`);
    const statusSpan = document.createElement('span');
    statusSpan.className = 'run-status';
    let startTime = Date.now();
    let timer;

    // 更新运行状态
    function updateStatus() {
        const duration = Math.floor((Date.now() - startTime) / 1000);
        statusSpan.innerHTML = `<span class="status-dot running"></span> 运行中 (${duration}s)`;
    }

    outputContainer.style.display = 'block';
    outputContainer.innerHTML = '';
    outputContainer.appendChild(statusSpan);
    
    updateStatus();
    timer = setInterval(updateStatus, 1000);
    runBtn.disabled = true;

    fetch(`/run_script/${scriptName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ file: selectedFile })
    })
    .then(response => response.json())
    .then(data => {
        clearInterval(timer);
        const duration = Math.floor((Date.now() - startTime) / 1000);
        
        // 保存运行记录
        saveRunHistory(scriptName, data, duration);
        
        // 显示简要结果
        if (data.error) {
            statusSpan.innerHTML = `<span class="status-dot error"></span> 运行失败 (${duration}s)`;
        } else {
            const success = data.returncode === 0;
            statusSpan.innerHTML = `<span class="status-dot ${success ? 'success' : 'error'}"></span> 
                                  ${success ? '运行完成' : '运行异常'} (${duration}s)`;
        }
        
        // 添加查看历史按钮
        const historyBtn = document.createElement('button');
        historyBtn.className = 'history-btn';
        historyBtn.textContent = '查看历史记录';
        historyBtn.onclick = () => showHistoryDialog(scriptName);
        outputContainer.appendChild(historyBtn);
    })
    .catch(error => {
        clearInterval(timer);
        const duration = Math.floor((Date.now() - startTime) / 1000);
        statusSpan.innerHTML = `<span class="status-dot error"></span> 运行失败 (${duration}s)`;
        
        // 保存错误记录
        saveRunHistory(scriptName, { error: error.toString() }, duration);
    })
    .finally(() => {
        runBtn.disabled = false;
    });
}

// 切换虚拟环境
function changeVenv(scriptName, venvName) {
    fetch(`/change_venv/${scriptName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ venv: venvName })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            // 显示成功消息
            const outputContainer = document.getElementById(`output-${scriptName}`);
            outputContainer.style.display = 'block';
            outputContainer.textContent = `已切换到${venvName ? venvName : '系统Python'}`;
            setTimeout(() => {
                outputContainer.style.display = 'none';
            }, 2000);
        }
    })
    .catch(error => {
        alert('切换虚拟环境失败: ' + error);
    });
} 